<template>
  <div>
    <el-dialog :title="batchList ? '告警批量处理' : '告警处理'" :visible.sync="dialogVisible" width="520px"
      :before-close="closeAddDialog" :modal-append-to-body="false" :close-on-click-modal="false">
      <el-form :model="ruleForm" :rules="rules" ref="refalarmHandleInfo" label-width="110px">
        <el-form-item size="small" label="告警类型" prop="alarmFactor">
          <!-- <el-autocomplete
            clearable
            @clear="clearAlarmFactor"
            v-model="ruleForm.alarmFactor"
            :fetch-suggestions="querySearch"
            placeholder="请选择"
            @select="handleSelect"
            style="width: 330px"
            :maxlength="10"
          ></el-autocomplete> -->
          <el-radio v-model="ruleForm.alarmFactor" label="真实告警">真实告警</el-radio>
          <el-radio v-model="ruleForm.alarmFactor" label="误报" style="margin-left: 0">误报</el-radio>
          <el-radio v-model="ruleForm.alarmFactor" label="测试" style="margin-left: 0">测试</el-radio>
          <el-radio v-if="alarmHandleInfo.subDeviceCode != '' && fcrDutyUserRelatedVO" v-model="ruleForm.alarmFactor"
            label="转工单" style="margin-left: 0">转工单</el-radio>
        </el-form-item>

        <el-form-item size="small" label="处理人" v-if="ruleForm.alarmFactor == '转工单'" prop="handleUserId">
          <el-select v-model="ruleForm.handleUserId" filterable placeholder="请选择处理人" style="width: 100%" size="small"
            clearable>
            <el-option v-for="(item, i) in fcrDutyUserRelatedVO" :key="i" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item size="small" label="照片" v-if="!batchList && ruleForm.alarmFactor != '转工单'">
          <el-upload :class="{ disabled: uploadDisabled }" :on-remove="handleRemove" :on-change="uploadSectionFile"
            :action="baseUrl" list-type="picture-card" accept=".jpg,.png" :on-preview="handlePictureCardPreview"
            :headers="headers" :before-upload="beforeAvatarUpload" :on-success="handleSuccessFunction" :limit="1"
            :on-exceed="handleExceedScene" :file-list="fileList">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item size="small" label="反馈内容" v-if="!batchList && ruleForm.alarmFactor != '转工单'">
          <el-input maxlength="30" rows="3" type="textarea" v-model="ruleForm.feedback" resize="none"
            :autosize="{ minRows: 2, maxRows: 5 }"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="ruleForm.status != 1">
        <el-button size="small" @click="closeAddDialog" class="cancel-button">取 消</el-button>
        <el-button size="small" class="confirm-button" @click="addSubmit">确 定</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-else>
        <el-button size="small" @click="closeAddDialog">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible2">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import {
  reqAlarmHandle,
  reqClosedLoop,
  reqAlarmbatchHandling,
  reqBatchClosedLoop,
  reqGetDetails,
} from "@/api/api";
import { mapState } from "vuex";
import asc from "@utils/asc.js"; //加密解密

export default {
  props: ["alarmHandleInfo", "batchList"],
  data() {
    return {
      fileList: [],
      headers: {
        token: asc.decrypt(sessionStorage.getItem("token")),
      },
      dialogVisible2: false,
      dialogImageUrl: "",
      ruleForm: {
        alarmFactor: "真实告警",
        feedback: "",
        pic: "",
        userId: "",
        handleUserId: ""
      },
      dialogVisible: false,
      // 表单验证规则
      rules: {
        alarmFactor: [
          {
            required: true,
            message: "请选择告警类型",
            trigger: ["blur", "change"],
          },
        ],
        handleUserId: [
          {
            required: true,
            message: "请选择处理人",
            trigger: "change",
          },
        ],
        // feedback: [{ required: false, trigger: "blur" }],
        // pic: [
        //   {
        //     required: true,
        //     message: "请选择照片",
        //     trigger: "change",
        //   },
        // ],
      },
      alarmFactorList: [
        {
          id: 0,
          name: "火警",
        },
        {
          id: 1,
          name: "误报",
        },
        {
          id: 2,
          name: "测试",
        },
        {
          id: 3,
          name: "其他",
        },
      ],
      restaurants: [],
      uploadDisabled: false, //加号默认显示
      fcrDutyUserRelatedVO: []
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    // alarmHandleInfo: {
    //   handler(val) {
    //     // console.log(val);
    //     // this.AlarmHandleResult()
    //   },
    // },
    dialogVisible(e) {
      if (e) {
        this.uploadDisabled = false;
        if (this.alarmHandleInfo.subDeviceCode != '') {
          this.getGetDetails();//根据imei获取消控室详情
        }
      }
    },
  },
  methods: {
    // 消控室列表
    async getGetDetails() {
      let res = await reqGetDetails(this.alarmHandleInfo.imei);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // console.log(res, 'res');
      this.fcrDutyUserRelatedVO = res.data.info.fcrDutyUserRelatedVO || [];
    },
    uploadSectionFile(file, fileList) {
      if (fileList.length >= 1) {
        this.uploadDisabled = true; //隐藏加号
      }
    },
    //删除照片
    handleRemove(file) {
      this.ruleForm.pic = "";
      setTimeout(() => {
        this.uploadDisabled = false;
      }, 1000);
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    loadAll() {
      return [
        { value: "火警" },
        { value: "误报" },
        { value: "测试" },
        { value: "其它" },
      ];
    },
    handleSelect(item) {
      // console.log(item);
    },
    // 清除告警因素
    clearAlarmFactor() {
      this.restaurants = this.loadAll();
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible2 = true;
    },
    // 上传文件之前的钩子
    beforeAvatarUpload(file) {
      let isJPG = true;
      let isLt = file.size / 1024 < 20000; // 判断是否小于500Kb
      if (file.type !== "image/png" && file.type !== "image/jpeg") {
        this.uploadDisabled = false;
        this.$modal.notifyWarning("图片只能是 jpg/png 格式!");
        isJPG = false;
        return isJPG;
      } else if (!isLt) {
        this.$modal.notifyWarning("图片大小不能超过20MB! 请重新上传");
        this.uploadDisabled = false;
        isJPG = false;
      }
      return isJPG;
    },
    // 上传成功
    handleSuccessFunction(response, file, fileList) {
      this.ruleForm.pic = file.response.data.url;
    },
    // 文件超出个数限制时的钩子
    handleExceedScene() {
      this.$modal.notifyWarning(`照片只能上传一张`);
    },
    // 查看告警处理结果
    // async AlarmHandleResult(){
    //   let res = await reqAlarmHandleResult(this.alarmHandleInfo.id);
    //   if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
    //   if(res.data.row.remarks){
    //     this.editInfo.remarks=res.data.row.remarks;
    //     this.editInfo.alarmFactor=res.data.row.alarmFactor;
    //     this.alarmHandleInfo.status=1
    //   }else{
    //     this.alarmHandleInfo.status=0
    //   }
    // },
    // 点击新增
    addSubmit() {
      this.$refs.refalarmHandleInfo.validate(async (valid) => {
        if (!valid) return;
        let params;
        if (this.batchList) {
          // 批量
          params = {
            idList: this.batchList,
            alarmFactor: this.ruleForm.alarmFactor,
            userId: this.user.userId,
          };
          const res = await reqAlarmbatchHandling(params);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);

          //批量完结
          let res2 = await reqBatchClosedLoop({
            idList: this.batchList,
          });
          if (res2.code !== 20000)
            return this.$modal.notifyWarning(res2.message);
          this.$parent.clearWarn();
        } else {
          if (this.ruleForm.alarmFactor == '转工单') {
            if (this.ruleForm.handleUserId == '') return this.$modal.notifyWarning('请选择处理人');
            params = {
              id: this.alarmHandleInfo.id,
              alarmFactor: this.ruleForm.alarmFactor,
              feedback: this.ruleForm.feedback,
              pic: this.ruleForm.pic,
              userId: this.user.userId,
              handleUserId: this.ruleForm.handleUserId,
            }
          } else {
            params = {
              id: this.alarmHandleInfo.id,
              alarmFactor: this.ruleForm.alarmFactor,
              feedback: this.ruleForm.feedback,
              pic: this.ruleForm.pic,
              userId: this.user.userId,
            }
          }
          const res = await reqAlarmHandle(params);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);

          if (this.ruleForm.alarmFactor != '转工单') {
            // 完结
            let res2 = await reqClosedLoop({
              id: this.alarmHandleInfo.id,
            });
            if (res2.code !== 20000)
              return this.$modal.notifyWarning(res2.message);
          }

          setTimeout(() => {
            this.$parent.AlarmHandleResult(); //更新告警列表
            if (this.ruleForm.alarmFactor != '转工单') {
            this.$emit("changstatus",3);
            }else{
            this.$emit("changstatus",2);
            }
          }, 100);
        }
        this.$modal.notifySuccess("处理成功");
        this.closeAddDialog();
      });
    },
    // 点击关闭弹框
    closeAddDialog() {
      this.dialogVisible = false;
      this.fileList = [];
      (this.ruleForm = {
        alarmFactor: "真实告警",
        feedback: "",
        pic: "",
        userId: "",
      }),
        this.$refs.refalarmHandleInfo.resetFields();
      // this.uploadDisabled = false;
    },
  },
  mounted() {
    this.restaurants = this.loadAll();
  },
  created() {
    this.baseUrl = `${this.$baseURL_copy}file/upload`;
  },
  deactivated() {
    if (this.$refs.refalarmHandleInfo != null) {
      this.closeAddDialog();
    }
    this.dialogVisible2 = false;
  },
};
</script>

<style lang="less" scoped>
@import url("../../common.less");

::v-deep .el-dialog__body {
  // min-height: 120px !important;
  min-height: 50px !important;
}

/deep/ .el-textarea__inner {
  resize: none;
}

// 隐藏加号
/deep/ .disabled .el-upload--picture-card {
  display: none !important;
}

// 单选按钮
::v-deep .el-radio__input.is-checked+.el-radio__label {
  color: #7367f0;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #7367f0;
  background: #7367f0;
}

/* 未选中状态的样式 */
::v-deep .el-radio {
  color: #cfd3ec;
}
</style>
